package trans

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

//type Youdao interface {
//	Trans() string
//}
//
//type Translation struct {
//	words string
//	from  string
//	to    string
//}

const (
	ZH   = "zh-CHS"
	EN   = "en"
	JA   = "ja"
	AUTO = "auto"
)

const (
	signType  string = "v3"
	//appKey           = "14c2189227c836bb"
	//appSecret        = "4fG68nJEKtQGplRuyteMVusRNGhaSMnW"
	appKey           = "7b9be2c20b270d20"
	appSecret        = "74Q8xHocjOspJnXOX53VOXCzcH28uIMU"
)

type Config struct {
	AppKey    string `json:"appKey"`
	AppSecret string `json:"appSecret"`
}

type DictWeb struct {
	Key   string   `json:"key"`
	Value []string `json:"value"`
}

type DictBasic struct {
	UsPhonetic string   `json:"us-phonetic"`
	Phonetic   string   `json:"phonetic"`
	UkPhonetic string   `json:"uk-phonetic"`
	UkSpeech   string   `json:"uk-speech"`
	UsSpeech   string   `json:"us-speech"`
	Explains   []string `json:"explains"`
}

type DictResp struct {
	ErrorCode    string                 `json:"errorCode"`
	Query        string                 `json:"query"`
	Translation  []string               `json:"translation"`
	Basic        DictBasic              `json:"basic"`
	Web          []DictWeb              `json:"web,omitempty"`
	Lang         string                 `json:"l"`
	Dict         map[string]interface{} `json:"dict,omitempty"`
	Webdict      map[string]interface{} `json:"webdict,omitempty"`
	TSpeakUrl    string                 `json:"tSpeakUrl,omitempty"`
	SpeakUrl     string                 `json:"speakUrl,omitempty"`
	ReturnPhrase []string               `json:"returnPhrase,omitempty"`
}

func Trans(words, from, to string) string {
	var err error
	salt := uuid.NewV4().String()
	input := truncate(words)
	stamp := time.Now().Unix()
	curtime := strconv.FormatInt(stamp, 10)
	//instr := config.AppKey + input + salt.String() + strconv.FormatInt(stamp, 10) + config.AppSecret
	instr := appKey + input + salt + curtime + appSecret
	sig := sha256.Sum256([]byte(instr))
	var sigstr string = HexBuffToString(sig[:])

	data := make(url.Values, 0)
	data["q"] = []string{words}
	data["from"] = []string{from}
	data["to"] = []string{to}
	data["appKey"] = []string{appKey}
	data["salt"] = []string{salt}
	data["sign"] = []string{sigstr}
	data["signType"] = []string{signType}
	data["curtime"] = []string{curtime}

	var resp *http.Response
	resp, err = http.PostForm("https://openapi.youdao.com/api", data)
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}

	var dictResp DictResp
	json.Unmarshal(body, &dictResp)

	//show(&dictResp)

	translation := dictResp.Translation
	if len(translation) > 0 {
		return string(translation[0])
	} else {
		return ""
	}
}

func show(resp *DictResp) {
	if resp.ErrorCode != "0" {
		fmt.Println("请输入正确的数据")
	}
	fmt.Println("@", resp.Query)

	if resp.Basic.UkPhonetic != "" {
		fmt.Println("英:", "[", resp.Basic.UkPhonetic, "]")
	}
	if resp.Basic.UsPhonetic != "" {
		fmt.Println("美:", "[", resp.Basic.UsPhonetic, "]")
	}

	fmt.Println("[翻译]")
	for key, item := range resp.Translation {
		fmt.Println(key+1, ".", item)
	}

}

// --------------

/*
前置条件：
	signType=v3
	sign=sha256(应用ID+input+salt+curtime+应用密钥)
*/
/*
input 参数计算规则：
	当q长度大于20: input=q前10个字符 + q长度 + q后10个字符
	当q长度小于等于20: input=q字符串
*/
func truncate(q string) string {
	qarr := []rune(q)
	qlen := len(qarr)
	if qlen <= 20 {
		return q
	} else {
		return string(qarr[0:10]) + strconv.Itoa(qlen) + string(qarr[qlen-10:qlen])
	}
}

func HexBuffToString(buff []byte) string {
	var ret string
	for _, value := range buff {
		str := strconv.FormatUint(uint64(value), 16)
		if len([]rune(str)) == 1 {
			ret = ret + "0" + str
		} else {
			ret = ret + str
		}
	}
	return ret
}
